package cn.pink.core.support;

import java.io.File;
import java.io.FileFilter;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 通过给定的包名，来得到包下的全部CLASS类
 * @author Pink
 */
public class ClassFinder {

    /**
     * 将从配置文件中读取的形如org.jow转成org/jow路径格式
     */
    public static String packageToPath(String packageName) {
        return packageName.replaceAll("\\.", "/");
    }

    /**
     * 获取默认包(cn.pink)下的全部class
     */
    public static List<Class<?>> getAllClass() {
        return getAllClass("cn.pink");
    }

    /**
     * 读取包内所有的类获取class对象，并根据指定的条件过滤
     */
    public static List<Class<?>> getAllClass(String pname) {
        Set<Class<?>> classes = new HashSet<Class<?>>();
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        String packageDirName = pname.replace('.', '/');

        try {
            Enumeration<URL> dirs = cl.getResources(packageDirName);
            while (dirs.hasMoreElements()) {
                URL url = dirs.nextElement();

                String protocol = url.getProtocol();

                if ("file".equals(protocol))
                    findByFile(cl, pname, URLDecoder.decode(url.getFile(), "utf-8"), classes);
                else if ("jar".equals(protocol))
                    findInJar(cl, pname, packageDirName, url, classes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<Class<?>> result = new ArrayList<>(classes);
        Collections.sort(result, (a, b) -> a.getName().compareTo(b.getName()));
        return result;
    }

    /**
     * 从文件获取java类
     */
    private static void findByFile(ClassLoader cl, String packageName, String filePath, Set<Class<?>> classes) {
        File dir = new File(filePath);
        if (!dir.exists() || !dir.isDirectory())
            return;

        File[] dirFiles = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.isDirectory() || file.getName().endsWith(".class");
            }
        });

        for (File file : dirFiles) {
            if (file.isDirectory()) {
                findByFile(cl, packageName + "." + file.getName(), file.getAbsolutePath(), classes);
            } else {
                try {
                    String className = packageName + "."
                            + file.getName().substring(0, file.getName().length() - 6);
                    if (className.contains("NavigationSystem")) {
                        continue;
                    }
                    Class<?> clazz = Class.forName(className);
//					Class<?> clazz = cl.loadClass(packageName + "."
//							+ file.getName().substring(0, file.getName().length() - 6));
                    classes.add(clazz);
                } catch (ExceptionInInitializerError e) {
                    // 这个没关系 是无法初始化类
                    e.printStackTrace();
                } catch (NoClassDefFoundError e) {
                    // 这个没关系 是无法初始化类
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取jar中的java类
     */
    private static void findInJar(ClassLoader cl, String pname, String packageDirName, URL url, Set<Class<?>> classes) {
        try {
            JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
            Enumeration<JarEntry> entries = jar.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();

                if (entry.isDirectory())
                    continue;

                String name = entry.getName();

                if (name.charAt(0) == '/')
                    name = name.substring(0);

                if (name.startsWith(packageDirName) && name.contains("/") && name.endsWith(".class")) {
                    name = name.substring(0, name.length() - 6).replace('/', '.');
                    try {
                        Class<?> clazz = cl.loadClass(name);

                        classes.add(clazz);
                    } catch (Throwable e) {
                        System.out.println("无法直接加载的类：" + name);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}